<script setup lang="js">
import { ref,onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import {Search, Tickets} from "@element-plus/icons-vue";
import {fetchResourceList,deleteResource} from "@/api/resource.js";
import {fetchListAllCate} from "@/api/resourceCategory.js";
import ResourceDialog from "@/views/permission/resource/components/resourceDialog.vue";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute();
const router = useRouter();
const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
  nameKeyword: null,
  urlKeyword: null,
  categoryId:null
};
const listQuery = Object.assign({}, defaultListQuery);

const formData = ref({
  nameKeyword: null,
  urlKeyword: null,
  categoryId:null
});
const categoryOptions = ref([])

const resourceList = ref([]);
const total = ref(0);

const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

onMounted(() => {
  getResourceList()
  getCategoryOptions()
})

const getResourceList = () => {
  fetchResourceList(listQuery).then(res => {
    resourceList.value = res.data.data.list;
    total.value = res.data.data.total;
  })
}

const getCategoryOptions = () => {
  fetchListAllCate().then(res => {
    let cateList = res.data.data;
    for (let i = 0; i < cateList.length; i++) {
      let cate = cateList[i];
      categoryOptions.value.push({
        value: cate.id,
        label: cate.name
      })
    }
  })
}

const handleSearch = () => {
  listQuery.pageNum = 1;
  listQuery.nameKeyword = formData.value.nameKeyword;
  listQuery.urlKeyword = formData.value.urlKeyword;
  listQuery.categoryId = formData.value.categoryId;
  getResourceList();
}

const handleResetSearch = () => {
  listQuery.pageNum = 1;
  listQuery.nameKeyword = null;
  listQuery.urlKeyword = null;
  listQuery.categoryId = null;
  formData.value = {
    nameKeyword: null,
    urlKeyword: null,
    categoryId:null
  };
  getResourceList();
}

const handleResourceCategory = () => {
  router.push({
    path: "/permission/resourceCategory",
  })
}

const handleAddResource = () => {
  updateDialogVisible.value = true;
  isEdit.value = false;
  resourceForm.value = {
    name: null,
    url: null,
    categoryId: null,
    description: null
  }
}

const handleUpdate = (row) => {
  updateDialogVisible.value = true;
  isEdit.value = true;
  resourceForm.value = {
    name: row.name,
    url: row.url,
    categoryId: row.categoryId,
    description: row.description
  };
  console.log(resourceForm.value);
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该资源吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteResource(row.id).then((res) => {
      ElMessage.warning(res.data.message);
      ElMessage.success('删除成功');
      getResourceList();
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};


// TODO: 分页操作方法
const handleSizeChange = (size) => {
  listQuery.pageSize = size;
  getResourceList();
}
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getResourceList();
}

const updateDialogVisible = ref(false);
const isEdit = ref(false);
const resourceForm = ref({
  name: null,
  url: null,
  categoryId: null,
  description: null
});
const handleCancel = () => {
  resourceForm.value = {
    name: null,
    url: null,
    categoryId: null,
    description: null
  };
  updateDialogVisible.value = false;
}


</script>

<template>
  <div class="resource-list">
    <!-- 筛选列表 -->
    <div class="resource-search">
      <div class="logo">
        <div class="logo-text">
          <el-icon>
            <Search/>
          </el-icon>
          <span>筛选搜索</span>
        </div>
        <div class="search-btn">
          <el-button type="primary" @click="handleSearch()">查询结果</el-button>
          <el-button icon="refresh" @click="handleResetSearch()">重置</el-button>
        </div>
      </div>
      <div class="search">
        <el-form :inline="true" ref="searchForm" v-model="formData" label-width="100px">
          <el-form-item label="资源名称：">
            <el-input v-model="formData.nameKeyword" class="input-width" placeholder="资源名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="资源路径：">
            <el-input v-model="formData.urlKeyword" class="input-width" placeholder="资源路径" clearable></el-input>
          </el-form-item>
          <el-form-item label="资源分类：">
            <el-select v-model="formData.categoryId" placeholder="全部" clearable class="input-width">
              <el-option v-for="item in categoryOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 添加按钮-->
    <div class="add-list">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
      <div class="add-btn">
        <el-button type="success" icon="tools" @click="handleResourceCategory()">资源分类</el-button>
        <el-button type="primary" icon="plus" @click="handleAddResource()">添加</el-button>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="resource-table">
      <el-table ref="resourceTable"
                :data="resourceList"
                style="width: 100%;" border>
        <el-table-column label="编号" width="100" align="center">
          <template #default={row}>{{row.id}}</template>
        </el-table-column>
        <el-table-column label="资源名称" align="center">
          <template #default={row}>{{row.name}}</template>
        </el-table-column>
        <el-table-column label="资源路径" align="center">
          <template #default={row}>{{row.url}}</template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template #default={row}>{{row.description}}</template>
        </el-table-column>
        <el-table-column label="添加时间" align="center">
          <template #default={row}>{{ formatDate(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default={row}>
            <el-button size="small"
                       type="primary"
                       icon="edit"
                       @click="handleUpdate(row)">编辑
            </el-button>
            <el-button size="small"
                       type="danger"
                       icon="delete"
                       @click="handleDelete(row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page-bar">
      <el-pagination
          background
          layout="total, sizes,prev, pager, next,jumper"
          :total="total"
          :page-sizes="[5,10,15,20]"
          v-model:page-size="listQuery.pageSize"
          v-model:current-page="listQuery.pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </div>

  <!-- 更新弹窗 -->
  <ResourceDialog
      v-model="updateDialogVisible"
      :isEdit="isEdit"
      :resourceForm="resourceForm"
      :categoryOptions="categoryOptions"
      @close="handleCancel"
      @refresh="getResourceList"
  />

</template>

<style scoped lang="scss">
.resource-list {
  margin-top: 20px;
  display: flex;
  flex-direction: column;

  .resource-search {
    //height: 100px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;

    .logo {
      width: 100%;
      font-size: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        margin: 0 8px;
      }

      .search-btn {
        margin-left: 30px;
        padding: 0 10px;
      }
    }

    .search {
      width: 100%;

      .el-form {
        margin: 20px;

        .el-form-item {
          width: 280px;
        }
      }
    }
  }

  .add-list {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .page-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0;

  }
}

.input-width {
  width: 400px;
}
</style>